module API::V2
  class Apps < Grape::API
    resource :apps do
      post ":mac/connect" do
        app = App.where(mac: params[:mac]).first_or_create
        if app
          connection = AppConnection.new params[:app_connection]
          connection.app = app
          if connection.save!
            app.update_attributes duration: app.duration+connection.duration
            present app.reload
          end
        else
          not_found!
        end
      end

      get ":mac/connection" do
        app = App.where(mac: params[:mac]).first
        present app
      end

      post :watch do
        watch = Watching.new params[:watching]
        if watch.save
          present :status, true
        else
          bad_request!("watching")
        end
      end
    end
  end
end